<?php
namespace Modules\Category\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Category\Entities\Category;

use Validator;
use ThrowException;

class CategoryController extends Controller
{
    public function index(Request $req, $categoryType)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['scopes'] = [
            'level' => 1,
            'type' => $categoryType
        ]; 

        $options['order_by'] = ['list_weight' => 'desc'];

        $options['with'] = ['sub_categories'];

        $options['only'] = [
            'id',
            'uuid',
            'thumb',
            'title',
            'sub_title',
            'list_weight',
            'is_listed',
            // 'description',
            'products_count',
            'sub_categories' => [
                '*' => [
                    'id',
                    'uuid',
                    'title',
                    'sub_title',
                    'thumb',
                ]
            ],
            'created_at'
        ];

        $list = Category::getList($options);

        return $list->generateListResponse();
    }

    public function store(Request $req, $categoryType)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        if ($req->input('parent_id'))
            $info['level'] = 2;

        $info['type'] = $categoryType;

        $item = Category::create($info);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $categoryTypeq, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Category::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);
        }

        return [];
    }

    public function destroy(Request $req, $categoryType, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Category::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
